﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using HtmlAgilityPack;
using HttpCode.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebReptile.baidu.Controllers.Dto;

namespace WebReptile.baidu.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DomainNameController : ControllerBase
    {
        private readonly IHttpClientFactory _clientFactory;
        public DomainNameController(IHttpClientFactory clientFactory)
        {
            _clientFactory = clientFactory;
        }

        [HttpPost]
        public async Task<ActionResult<List<DomainNameDto>>> GetAsync(DomainNameInput input)
        {

            List<DomainNameDto> resultLinks = new List<DomainNameDto>();
            HttpHelpers httpHelpers = new HttpHelpers();
            HttpItems items = new HttpItems();
            input.Page = input.Page ?? 10;
            for (int i = 0; i < input.Page; i++)
            {
                int count = i * 10;
                string searchUrl = string.Format("https://www.baidu.com/s?wd={0}&pn={1}", HttpUtility.UrlEncode(input.Key), count);
                items.Url = searchUrl;
                items.Method = "Get";
                HttpResults hr = httpHelpers.GetHtml(items);
                //解析数据
                HtmlDocument doc = new HtmlDocument();
                //加载html
                doc.LoadHtml(hr.Html);
                HtmlNodeCollection itemNodes = doc.DocumentNode.SelectNodes("/html/body/div[@id='wrapper']/div[@id='wrapper_wrapper']/div[@id='container']/div[@id='content_left']/div");

                foreach (var item in itemNodes)
                {
                    if (item.Id == "rs_top_new") continue;
                    if (item.InnerText.Contains("最新相关信息")) continue;
                    var dto = await GetInfoAsync(item);
                    if (dto.WebName == "空" || dto.DomainName == "空") continue;
                    resultLinks.Add(dto);
                }
            }
            return resultLinks;
        }
        [HttpGet]
        public async Task<DomainNameDto> GetInfoAsync(HtmlNode node)
        {
            //获取标题
            var nodeTitle = node.SelectSingleNode("h3");
            string head = "空";
            string title = "空";
            string homeName = null;
            if (nodeTitle !=null)
            {
                title = nodeTitle.InnerText;
            }
            //  普通的地址
            var nodeUrl = node.SelectSingleNode("div[@class='f13']/a");
            if (nodeUrl != null)
            {
                head = nodeUrl.InnerText;
            }
            else
            {
                //  百度百科的地址
                nodeUrl = node.SelectSingleNode("div[@class='c-row']/div[@class='c-span18 c-span-last']/p[last()]/span[1]");
                if (nodeUrl != null)
                {
                    head = nodeUrl.InnerText;
                }
                else
                {
                    //  带图的左右
                    nodeUrl = node.SelectSingleNode("div[last()]/div[last()]/div[last()]/a");
                    if(nodeUrl !=null)
                    {
                        head = nodeUrl.InnerText;
                    }
                    else
                    {
                        //  百度图片
                        nodeUrl = node.SelectSingleNode("div[last()]/span/span[1]");
                        if(nodeUrl != null)
                        {
                            head = nodeUrl.InnerText;
                        }
                        else
                        {
                            //  百度爱采购
                            nodeUrl = node.SelectSingleNode("div[2]/a");
                            if(nodeUrl != null)
                            {
                                head = nodeUrl.InnerText;
                            }
                            else
                            {
                                //  中关村
                                nodeUrl = node.SelectSingleNode("div[last()]/span");
                                if (nodeUrl != null)
                                {
                                    head = nodeUrl.InnerText;
                                }
                            }
                        }
                    }
                }
            }

            //修改
            string patIsWebName = @"^.source-icon";
            string patHttps = @"^https://";
            bool IsWebName = false;
            IsWebName = Regex.IsMatch(head, patIsWebName);
            if (IsWebName)
            {
                // TodoVisited Web
              head = await GetVisitedUrlAsync(node);
                var nodeHomeName = nodeUrl.SelectSingleNode("span");
                homeName = nodeHomeName?.InnerText;


            }
            else
            {
                bool IsHttp = Regex.IsMatch(head, patHttps);
                if (IsHttp)
                {
                    head = head.Substring(8);
                    if (head.IndexOf("/") != -1)
                    {
                        head = head.Substring(0, head.IndexOf("/"));
                        if (head.Contains(@"..."))
                        {
                            head = await GetVisitedUrlAsync(node);
                        }
                        else
                        {
                            if (head != "空")
                            {
                                head = "http://" + head;
                            }
                         
                        }
                    }
                    else
                    {
                        if (head.Contains(@"..."))
                        {
                            head = await GetVisitedUrlAsync(node);
                        }
                        else
                        {
                            if (head != "空")
                            {
                                head = "http://" + head;
                            }
                        }
                    }

                }
                else
                {
                    if (head.IndexOf("/") != -1)
                    {
                        head = head.Substring(0, head.IndexOf("/"));
                        if (head.Contains(@"..."))
                        {
                            head = await GetVisitedUrlAsync(node);
                        }
                        else
                        {
                            if (head != "空")
                            {
                                head = "http://" + head;
                            }
                        }
                    }
                    else
                    {
                        if (head.Contains(@"..."))
                        {
                            head = await GetVisitedUrlAsync(node);
                        }
                        else
                        {
                            if (head != "空")
                            {
                                head = "http://" + head;
                            }
                        }
                    }
                }

            }
            DomainNameDto dto = new DomainNameDto
            {
                DomainName = head?.Trim(),
                WebName = title?.Trim(),
                HomeName = homeName?.Trim()
            };
            return dto;
        }
        [HttpPut]
        public async Task<string> GetVisitedUrlAsync(HtmlNode node)
        {
            string head = "空";
            //获取标题
            var nodeTitle = node.SelectSingleNode("h3");

            if (nodeTitle != null)
            {
                var nodetitleUrl = nodeTitle.InnerHtml;
                int a = nodetitleUrl.IndexOf("href=");
                int b = nodetitleUrl.IndexOf("target") - nodetitleUrl.IndexOf("href=");
                string fullUrl = nodetitleUrl.Substring(a + 6, b - 8);
                //获取域名
                string detail = fullUrl;
                var request = new HttpRequestMessage(HttpMethod.Get, fullUrl);
                var cur = _clientFactory.CreateClient();
                try
                {
                    var response = await cur.SendAsync(request);
                    head = response.RequestMessage.RequestUri.Scheme + "://" + response.RequestMessage.RequestUri.Host;
                }
                catch (Exception)
                {
                    head = "请求超时" + fullUrl;
                }
            }
            return head;

        }

    }
}